﻿using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace down2App
{
    public delegate void dgt_cbk(JToken t);
    public delegate void dgt_msg(string t);
    public delegate void dgt_ent(string t);

    public partial class Form1 : Form
    {
        /// <summary>
        /// 全局队列表
        /// </summary>
        Dictionary<string, FileDowner> tasks = new Dictionary<string, FileDowner>();
        HttpDownloaderAppLib.DownloaderPartitionClass down2 = null;
        JObject m_cfg = null;//全局配置

        /// <summary>
        /// 下载路径
        /// </summary>
        string m_folder = string.Empty;

        public Form1()
        {
            InitializeComponent();

            this.down2 = new HttpDownloaderAppLib.DownloaderPartitionClass();
            this.down2._IDownPartitionEvents_Event_recvMessage += Down2__IDownPartitionEvents_Event_recvMessage;
            var cfgPath = Path.Combine( Directory.GetCurrentDirectory() , "config.js");
            var cfgData = File.ReadAllText(cfgPath);
            this.m_cfg = JObject.Parse(cfgData);
            this.init_config(cfgData);
        }

        void show_msg(string t)
        {
            Action ac = () =>
            {
                this.m_rtbMsg.AppendText(t + "\n");
            };
            this.Invoke(ac);
        }

        void init_config(string cfgData)
        {
            JObject o = new JObject();
            o["name"] = "init";
            o["config"] = JObject.Parse(cfgData);
            this.down2.postMessage(o.ToString());
        }

        private void btnSetFolder_Click(object sender, EventArgs e)
        {
            JObject o = new JObject();
            o["name"] = "open_folder";
            this.down2.postMessage(o.ToString());
        }

        private void btnDown_Click(object sender, EventArgs e)
        {
            if(string.IsNullOrEmpty(this.m_folder))
            {
                MessageBox.Show("未设置下载目录");
                return;
            }

            string url = this.tbUrl.Text.Trim();
            if(!string.IsNullOrEmpty( url))
            {
                this.addUrl(url);
            }
        }

        /// <summary>
        /// 存在同名文件
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        bool existName(string name)
        {
            foreach(var t in tasks)
            {
                if(t.Value.fileSvr.nameLoc == name)
                {
                    return true;
                }
            }
            return false;
        }
        void addUrl(string url)
        {
            JObject o = new JObject();
            o["name"] = "add_url";
            //o["nameLoc"] = "test";
            o["fileUrl"] = url;
            o["folderLoc"] = this.m_folder;
            this.down2.postMessage(o.ToString());
        }

        /// <summary>
        /// 触发事件：add_json
        /// 数据格式：https://gitee.com/xproer/down2-li-si-chen-web/blob/2.4.21/WebContent/json.log
        /// </summary>
        /// <param name="url"></param>
        void addJsonUrl(string url)
        {
            JObject o = new JObject();
            o["name"] = "add_json_url";
            //o["nameLoc"] = "test";
            o["fileUrl"] = url;
            this.down2.postMessage(o.ToString());
        }

        void del_work(string id)
        {
            Action ac = () =>
            {
                this.tasks.Remove(id);
            };
            this.Invoke(ac);
        }

        private void Down2__IDownPartitionEvents_Event_recvMessage(string newVal)
        {
            this.m_rtbMsg.AppendText(newVal);

            var o = JToken.Parse(newVal);
            var name = o["name"].ToString();
            if (name == "open_folder")
            {
                this.ent_sel_folder(o);
            }
            else if (name == "down_recv_size") this.ent_down_recv_size(o);
            else if (name == "down_recv_name") this.ent_down_recv_name(o);
            else if (name == "init_end") this.ent_init_end(o);
            else if (name == "add_file") this.ent_add_file(o);
            else if (name == "add_folder") this.ent_add_folder(o);
            else if (name == "add_url") this.ent_add_url(o);
            else if (name == "add_urls_end") this.ent_add_urls_end(o);
            else if (name == "add_json") this.ent_add_json(o);
            else if (name == "query_process") this.ent_query_process(o);
            else if (name == "query_end") this.ent_query_end(o);
            else if (name == "down_begin") this.ent_down_begin(o);
            else if (name == "down_process") this.ent_down_process(o);
            else if (name == "down_error") this.ent_down_error(o);
            else if (name == "down_complete") this.ent_down_complete(o);
            else if (name == "down_stoped") this.ent_down_stoped(o);
            else if (name == "queue_complete") this.ent_queue_complete(o);
            else if (name == "queue_begin") this.ent_queue_begin(o);
            else if (name == "queue_end") this.ent_queue_end(o);
            else if (name == "load_complete") this.ent_load_complete(o);
            else if (name == "load_complete_edge") this.ent_load_complete_edge(o);
        }

        //event

        void ent_sel_folder(JToken o)
        {
            this.m_folder = o["path"].ToString();
        }

        void ent_down_recv_size(JToken o)
        {
            var id = o["id"].ToString();
            FileDowner fd = null;
            if(this.tasks.TryGetValue(id,out fd))
            {
                fd.down_recv_size(o);
            }
        }
        void ent_down_recv_name(JToken o)
        {
            var id = o["id"].ToString();
            FileDowner fd = null;
            if (this.tasks.TryGetValue(id, out fd))
            {
                fd.down_recv_name(o);
            }
        }

        void ent_init_end(JToken o)
        {
            var id = o["id"].ToString();
            FileDowner fd = null;
            if (this.tasks.TryGetValue(id, out fd))
            {
            }
        }

        void ent_add_file(JToken o)
        {
                this.show_msg("------添加文件成功------");
            //fileUrl,nameLoc,sizeSvr,id
            FileDowner d = new FileDowner(this.down2);
            d.show_msg = this.show_msg;
            d.fileSvr.fromJson(o);
            this.tasks.Add(d.fileSvr.id, d);
        }
        void ent_add_folder(JToken o) { }

        /// <summary>
        /// 添加URL成功，
        /// </summary>
        /// <param name="o"></param>
        void ent_add_url(JToken o)
        {
            //fileUrl,nameLoc,sizeSvr,id
            FileDowner d = new FileDowner(this.down2);
            d.show_msg = this.show_msg;
            d.downComplete = del_work;
            d.fileSvr.fromJson(o);
            this.tasks.Add(d.fileSvr.id, d);

            d.down();
        }
        void ent_add_urls_end(JToken o) { }

        /// <summary>
        /// 添加JSON URL
        /// </summary>
        /// <param name="o"></param>
        void ent_add_json(JToken o) {
            this.show_msg("------添加JSON URL成功------");
            var id = o["id"].ToString();
        }

        void ent_query_process(JToken o)
        {
            var id = o["id"].ToString();
            FileDowner fd = null;
            if (this.tasks.TryGetValue(id, out fd))
            {
            }
        }

        void ent_query_end(JToken o)
        {
            var id = o["id"].ToString();
            FileDowner fd = null;
            if (this.tasks.TryGetValue(id, out fd))
            {
                fd.query_end(o);
            }
        }

        void ent_down_begin(JToken o)
        {
            var id = o["id"].ToString();
            FileDowner fd = null;
            if (this.tasks.TryGetValue(id, out fd))
            {
                fd.down_begin(o);
            }
        }

        void ent_down_process(JToken o)
        {
            var id = o["id"].ToString();
            FileDowner fd = null;
            if (this.tasks.TryGetValue(id, out fd))
            {
                fd.down_process(o);
            }
        }

        void ent_down_error(JToken o)
        {
            var id = o["id"].ToString();
            FileDowner fd = null;
            if (this.tasks.TryGetValue(id, out fd))
            {
                fd.down_error(o);
            }
        }

        void ent_down_complete(JToken o)
        {
            var id = o["id"].ToString();
            FileDowner fd = null;
            if (this.tasks.TryGetValue(id, out fd))
            {
                fd.down_complete(o);
            }
        }

        void ent_down_stoped(JToken o)
        {
            var id = o["id"].ToString();
            FileDowner fd = null;
            if (this.tasks.TryGetValue(id, out fd))
            {
                fd.down_stoped(o);
            }
        }

        void ent_queue_complete(JToken o)
        {
        }

        void ent_queue_begin(JToken o) { }

        void ent_queue_end(JToken o) { }

        void ent_load_complete(JToken o)
        {
            //this.show_msg("------控件加载成功------");
        }

        void ent_load_complete_edge(JToken o)
        {
            //this.show_msg("------控件加载成功------");
        }

        private void btnDownJsonUrl_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(this.m_folder))
            {
                MessageBox.Show("未设置下载目录");
                return;
            }

            string url = this.tbUrl.Text.Trim();
            if (!string.IsNullOrEmpty(url))
            {
                this.addJsonUrl(url);
            }
        }
    }
}
